<template>
  <div v-if="!!formItemProps">
    <ElDivider> 表单项设置</ElDivider>
    <ElForm :model="formItemProps" label-width="80px">
      <ElFormItem prop="table" label="业务实体">
        <Select v-model="entityId" disabled :options="entityList" label-name="entityName" value-name="id"></Select>
      </ElFormItem>
      <ElFormItem prop="column" label="数据字段">
        <Select
          v-model="formItemProps.prop"
          :options="fieldList"
          label-name="fieldName"
          value-name="fieldCode"
          style="width: 100%"
          @change="value => handleChange(value)"
        ></Select>
      </ElFormItem>
      <ElFormItem prop="label" label="标签名称">
        <ElInput v-model="formItemProps.label"></ElInput>
      </ElFormItem>
      <ElFormItem prop="required" label="是否必填">
        <ElSwitch v-model="formItemProps.required" :inline-prompt="true" active-text="是" inactive-text="否"></ElSwitch>
      </ElFormItem>
    </ElForm>
  </div>
</template>

<script setup lang="ts" name="FormItemPanel">
import { ElForm, ElFormItem, ElDivider, ElInput, ElSwitch } from "element-plus";
import { computed, ref, watch } from "vue";
import { Select } from "@/components/Form";
import entityApi from "@/views/micro/entity/api";
const props = defineProps({
  designer: {
    type: Object
  }
});
const formItemProps = computed(() => props.designer!.widget?.selectedWidget?.formItemProps);
const entityId = computed(() => {
  let entityId = formItemProps.value?.entityId;
  if (!entityId) {
    entityId = props.designer!.global.entityId;
  }
  return entityId;
});
const entityList = ref([]);
const fieldList = ref([]);
watch(
  () => entityId.value,
  async id => {
    if (id) {
      entityList.value = [await entityApi.query(id)];
      fieldList.value = await entityApi.listField({ id });
    } else {
      entityList.value = [];
      fieldList.value = [];
    }
  },
  {
    immediate: true
  }
);
const handleChange = value => {
  for (const field of fieldList.value) {
    if (field.fieldCode === value) {
      formItemProps.value.label = field.fieldName;
      break;
    }
  }
};
</script>

<style scoped></style>
